<?php

class QSrepository extends QData 
{
	/**
	 * The connection
	 *
	 * @var QSqlConnection
	 */
	private $connection;
	/**
	 * The database
	 *
	 * @var string
	 */
	private $database;
	/**
	 * Tables prefix
	 *
	 * @var string
	 */
	private $tables_prefix;
	
	private $object_types;
	
	private static $Default;

	/**
	 * The constructor for QSrepository
	 *
	 * @param QSqlConnection $connection
	 * @param string $database
	 * @param string $tables_prefix
	 */
	public function __construct(QSqlConnection $connection, $set_default = false, $database = null, $tables_prefix = "ws_")
	{
		$this->connection = $connection;
		$this->database = $database;
		$this->tables_prefix = $tables_prefix;
		
		$this->init($set_default);
	}
	
	public function init($set_default = false)
	{
		// grab the data types info : object , properties , enum data
		
		$result = $this->connection->query("SELECT `id`,`name`,`scalar`,`fixed_props`,`id_parent`,`sql_type`,`sql_size`,`embedded`,`index` 
			FROM `{$this->tables_prefix}def_objects` ORDER BY `id_parent`");
		
		while ($r = $this->connection->fetchArray($result))
			$this->object_types[$r["id"]] = new QSobjectType($this, $r);
			
		if ($set_default)
			self::$Default = $this;
	}
	
	public function updateScalarTables()
	{
		foreach ($this->object_types as $object)
		{
			if ($object->isScalar())
			{
				// echo $object->getRepositoryTable()."<br>\n";
				$table_name = $object->getRepositoryTable();
				$this->connection->query("
					CREATE TABLE IF NOT EXISTS `{$table_name}` (
					  `id` int(10) unsigned NOT NULL auto_increment,
					  `val` ".$object->getSqlType().($object->getSqlSize() ? "({$object->getSqlSize()})" : "")." NULL,
					  PRIMARY KEY (`id`)
					  ".($object->getSqlIndex() ? ",KEY `val` (`val`)," : "")."
					) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
					");
			}
		}
	}

	public static function CreateRepository(QSqlConnection $connection, $database = null, $tables_prefix = "ws_", 
		$drop_if_exists = false)
	{
		if (!$database)
			$database = $connection->getDefaultDatabase();
		$connection->selectDb($database);

		if ($drop_if_exists)
		{
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}arrays`;");
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}def_enums`;");
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}objects`;");
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}objects_props`;");
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}def_objects`;");
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}def_props`;");
			$connection->query("DROP TABLE IF EXISTS `{$tables_prefix}def_accepted_types`;");
		}
		
		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}arrays` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `id_array` int(10) unsigned NOT NULL,
			  `id_item_type` int(10) unsigned NOT NULL,
			  `id_item` int(10) unsigned NOT NULL,
			  `order` int(10) unsigned NOT NULL,
			  PRIMARY KEY  (`id`),
			  KEY `id` (`id_array`),
			  KEY `id_item_type` (`id_item_type`),
			  KEY `id_item` (`id_item`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
			");
		
		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}def_enums` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `id_enum_type` int(10) unsigned NOT NULL,
			  `value` varchar(255) collate utf8_unicode_ci NOT NULL,
			  PRIMARY KEY  (`id`),
			  KEY `id_enum_type` (`id_enum_type`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
			");
		
		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}objects` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `id_type` int(10) unsigned NOT NULL,
			  PRIMARY KEY  (`id`),
			  KEY `id_type` (`id_type`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
			");
			
		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}objects_props` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `id_obj` int(10) unsigned NOT NULL,
			  `name` varchar(48) collate utf8_unicode_ci NOT NULL,
			  `id_type` int(10) unsigned NOT NULL,
			  `id_val` int(10) unsigned NOT NULL,
			  PRIMARY KEY  (`id`),
			  UNIQUE KEY `id_obj` (`id_obj`,`name`),
			  KEY `id_val` (`id_val`),
			  KEY `id_type` (`id_type`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
			");
			
		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}def_objects` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `name` varchar(48) collate utf8_unicode_ci NOT NULL,
			  `scalar` tinyint(1) NOT NULL default '0',
			  `fixed_props` tinyint(1) NOT NULL default '0',
			  `id_parent` int(10) unsigned NOT NULL default '0',
			  `sql_type` varchar(32) collate utf8_unicode_ci NOT NULL,
			  `sql_size` varchar(16) collate utf8_unicode_ci NOT NULL,
			  `embedded` tinyint(1) NOT NULL default '0',
			  `own_table` tinyint(1) NOT NULL default '0',
			  `index` tinyint(1) NOT NULL DEFAULT '0',
			  PRIMARY KEY  (`id`),
			  UNIQUE KEY `name` (`name`),
			  KEY `id_parent` (`id_parent`)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
			");
		
		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}def_props` (
			  `id` int(10) unsigned NOT NULL auto_increment,
			  `id_obj_type` int(10) unsigned NOT NULL,
			  `name` varchar(48) collate utf8_unicode_ci NOT NULL,
			  `is_array` tinyint(1) NOT NULL default '0',
			  PRIMARY KEY  (`id`),
			  UNIQUE KEY `id_obj_type` (`id_obj_type`,`name`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
			");

		$connection->query("
			CREATE TABLE IF NOT EXISTS `{$tables_prefix}def_accepted_types` (
			  `id_prop_type` int(10) unsigned NOT NULL,
			  `id_obj_type` int(10) unsigned NOT NULL,
			  PRIMARY KEY  (`id_prop_type`,`id_obj_type`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"
			);
		
		// set the predefined data
		$connection->query("INSERT INTO `{$tables_prefix}def_objects` (`id`, `name`, `scalar`, `fixed_props`, `id_parent`, `sql_type`, `sql_size`, `embedded`) VALUES
			(NULL, 'number', 1, 0, 0, 'DOUBLE', '', 1),
			(NULL, 'string', 1, 0, 0, 'VARCHAR', '255', 1),
			(NULL, 'text', 1, 0, 0, 'TEXT', '', 1),
			(NULL, 'blob', 1, 0, 0, 'BLOB', '', 1),
			(NULL, 'object', 0, 0, 0, 'INT', '', 1),
			(NULL, 'boolean', 1, 0, 0, 'BOOL', '', 1),
			(NULL, 'array', 0, 0, 0, 'INT', '', 1),
			(NULL, 'set', 0, 0, 0, 'INT', '', 1),
			(NULL, 'enum', 1, 0, 0, 'INT', '', 1),
			(NULL, 'datetime', 1, 0, 0, 'DATETIME', '', 1),
			(NULL, 'longtext', 1, 0, 0, 'LONGTEXT', '', 1),
			(NULL, 'longblob', 1, 0, 0, 'LONGBLOB', '', 1);
			");
		
		// set parent ids
		$id_parent = $connection->queryOneValue("SELECT `id` FROM `{$tables_prefix}def_objects` WHERE `name`='string'", "id");
		$connection->query("UPDATE `{$tables_prefix}def_objects` SET `id_parent`='{$id_parent}' WHERE `name`='text';");
		
		$id_parent = $connection->queryOneValue("SELECT `id` FROM `{$tables_prefix}def_objects` WHERE `name`='string'", "id");
		$connection->query("UPDATE `{$tables_prefix}def_objects` SET `id_parent`='{$id_parent}' WHERE `name`='longtext';");
		
		$id_parent = $connection->queryOneValue("SELECT `id` FROM `{$tables_prefix}def_objects` WHERE `name`='string'", "id");
		$connection->query("UPDATE `{$tables_prefix}def_objects` SET `id_parent`='{$id_parent}' WHERE `name`='enum';");

		$id_parent = $connection->queryOneValue("SELECT `id` FROM `{$tables_prefix}def_objects` WHERE `name`='blob'", "id");
		$connection->query("UPDATE `{$tables_prefix}def_objects` SET `id_parent`='{$id_parent}' WHERE `name`='longblob';");

		$id_parent = $connection->queryOneValue("SELECT `id` FROM `{$tables_prefix}def_objects` WHERE `name`='object'", "id");
		$connection->query("UPDATE `{$tables_prefix}def_objects` SET `id_parent`='{$id_parent}' WHERE `name`='array';");

		$id_parent = $connection->queryOneValue("SELECT `id` FROM `{$tables_prefix}def_objects` WHERE `name`='object'", "id");
		$connection->query("UPDATE `{$tables_prefix}def_objects` SET `id_parent`='{$id_parent}' WHERE `name`='set';");

		$repository = new QSrepository($connection, false, $database, $tables_prefix);
		$repository->updateScalarTables();
		
		return $repository;
	}
	
	public function getObjectTypeById($id)
	{
		if (!isset($this->object_types))
			return null;
		if (isset($this->object_types[$id]))
			return $this->object_types[$id];
		else 
			return null;
	}
	
	public static function GetDefaultRepository()
	{
		if (isset(self::$Default))
			return self::$Default;
		else 
			return null;
	}
	
	public function getTablesPrefix()
	{
		return $this->tables_prefix;
	}
	
	public function importDataFromTable($table, $column_mapping, $target, $database = null)
	{
		
	}
}


?>